<template>
  <el-dialog
    v-model="dialogVisible"
    title="新增文章"
    width="80%"
    :before-close="handleClose"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <el-form :model="articleForm" label-width="80px">
      <el-form-item label="标题" prop="title">
        <el-input v-model="articleForm.title" placeholder="请输入文章标题" />
      </el-form-item>
      <el-form-item label="内容" prop="content">
        <div class="editor-container">
          <Toolbar
            style="border-bottom: 1px solid #ccc"
            :editor="editorRef"
            :defaultConfig="toolbarConfig"
            :mode="mode"
          />
          <Editor
            style="height: 500px; overflow-y: hidden"
            v-model="articleForm.content"
            :defaultConfig="editorConfig"
            :mode="mode"
            @onCreated="handleCreated"
          />
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, shallowRef } from "vue";
import "@wangeditor/editor/dist/css/style.css";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { uploadFile } from "@/api/user/uploads";
import { createArticle } from "@/api/user/article";
import { useUserStore } from "@/stores/userStore";
import { ElMessage } from "element-plus";

const dialogVisible = ref(false);
const articleForm = ref({
  title: "",
  content: "",
});

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

// 内容 HTML
const valueHtml = ref("<p>hello</p>");

// 模式
const mode = ref("default");

// 工具栏配置
const toolbarConfig = {
  excludeKeys: [
    "group-video",
    "insertTable",
    "group-indent",
    "group-more-style",
  ],
};

// 编辑器配置
const editorConfig = {
  placeholder: "请输入内容...",
  MENU_CONF: {
    uploadImage: {
      async customUpload(file: File, insertFn: Function) {
        try {
          const response = await uploadFile(file);
          insertFn(response.data.file);
        } catch (error) {
          console.error("图片上传失败:", error);
        }
      },
    },
  },
};

// 组件销毁时，也及时销毁编辑器
const handleCreated = (editor: any) => {
  editorRef.value = editor;
};

const handleClose = () => {
  dialogVisible.value = false;
  articleForm.value = {
    title: "",
    content: "",
  };
};

const handleSubmit = async () => {
  if (!articleForm.value.title.trim()) {
    ElMessage.warning("请输入文章标题");
    return;
  }
  if (!articleForm.value.content.trim()) {
    ElMessage.warning("请输入文章内容");
    return;
  }

  try {
    const userStore = useUserStore();
    const userId = userStore.userInfo.id;
    if (!userId) {
      ElMessage.error("用户未登录");
      return;
    }

    await createArticle({
      title: articleForm.value.title,
      content: articleForm.value.content,
      userId: userId.toString(),
    });

    ElMessage.success("文章发布成功");
    handleClose();
  } catch (error) {
    console.error("发布文章失败:", error);
    ElMessage.error("发布文章失败，请稍后重试");
  }
};

const show = () => {
  dialogVisible.value = true;
};

defineExpose({
  show,
});
</script>

<style scoped>
.editor-container {
  border: 1px solid #ccc;
  z-index: 100;
}
</style>
